<?php
require_once 'header.php';

// 检查是否已登录
if (!isLoggedIn()) {
    $_SESSION['flash_message'] = '请先登录再查看个人信息';
    $_SESSION['flash_message_type'] = 'warning';
    header('Location: login.php');
    exit;
}

// 获取用户信息
$user = getCurrentUser();

// 处理表单提交 - 更新个人信息
$success_message = '';
$error_message = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $email = $_POST['email'] ?? '';
    $current_password = $_POST['current_password'] ?? '';
    $new_password = $_POST['new_password'] ?? '';
    $confirm_password = $_POST['confirm_password'] ?? '';
    
    // 验证电子邮件
    if (empty($email) || !filter_var($email, FILTER_VALIDATE_EMAIL)) {
        $error_message = '请输入有效的电子邮件地址';
    } else {
        // 更新电子邮件
        if ($email !== $user['email']) {
            // 检查邮箱是否已被其他用户使用
            $check_email = "SELECT id FROM users WHERE email = ? AND id != ?";
            $stmt = $conn->prepare($check_email);
            $stmt->bind_param("si", $email, $user['id']);
            $stmt->execute();
            $result = $stmt->get_result();
            
            if ($result->num_rows > 0) {
                $error_message = '该电子邮件地址已被注册';
            } else {
                $update_email = "UPDATE users SET email = ? WHERE id = ?";
                $stmt = $conn->prepare($update_email);
                $stmt->bind_param("si", $email, $user['id']);
                
                if ($stmt->execute()) {
                    $success_message = '电子邮件已成功更新';
                } else {
                    $error_message = '更新电子邮件时出错: ' . $stmt->error;
                }
            }
        }
        
        // 更新密码
        if (!empty($current_password) && !empty($new_password)) {
            // 验证当前密码
            $check_password = "SELECT password FROM users WHERE id = ?";
            $stmt = $conn->prepare($check_password);
            $stmt->bind_param("i", $user['id']);
            $stmt->execute();
            $result = $stmt->get_result();
            $user_data = $result->fetch_assoc();
            
            if (password_verify($current_password, $user_data['password'])) {
                // 验证新密码长度
                if (strlen($new_password) < 6) {
                    $error_message = '新密码长度至少为6个字符';
                } 
                // 验证两次密码输入是否一致
                elseif ($new_password !== $confirm_password) {
                    $error_message = '两次输入的新密码不一致';
                } else {
                    // 更新密码
                    $hashed_password = password_hash($new_password, PASSWORD_DEFAULT);
                    $update_password = "UPDATE users SET password = ? WHERE id = ?";
                    $stmt = $conn->prepare($update_password);
                    $stmt->bind_param("si", $hashed_password, $user['id']);
                    
                    if ($stmt->execute()) {
                        $success_message = '密码已成功更新';
                    } else {
                        $error_message = '更新密码时出错: ' . $stmt->error;
                    }
                }
            } else {
                $error_message = '当前密码不正确';
            }
        }
    }
    
    // 重新获取用户信息
    $user = getCurrentUser();
}
?>

<div class="container">
    <h1 class="mb-4">个人信息</h1>
    
    <div class="row">
        <div class="col-md-4 mb-4">
            <div class="card">
                <div class="card-header">
                    <h5 class="mb-0">账户信息</h5>
                </div>
                <div class="card-body">
                    <p><strong>用户名:</strong> <?php echo htmlspecialchars($user['username']); ?></p>
                    <p><strong>电子邮件:</strong> <?php echo htmlspecialchars($user['email']); ?></p>
                    <p><strong>注册时间:</strong> <?php echo date('Y-m-d H:i:s', strtotime($user['register_time'])); ?></p>
                </div>
            </div>
        </div>
        
        <div class="col-md-8">
            <div class="card">
                <div class="card-header">
                    <h5 class="mb-0">修改个人信息</h5>
                </div>
                <div class="card-body">
                    <?php if (!empty($success_message)): ?>
                    <div class="alert alert-success" role="alert">
                        <?php echo $success_message; ?>
                    </div>
                    <?php endif; ?>
                    
                    <?php if (!empty($error_message)): ?>
                    <div class="alert alert-danger" role="alert">
                        <?php echo $error_message; ?>
                    </div>
                    <?php endif; ?>
                    
                    <form action="profile.php" method="post">
                        <div class="form-group">
                            <label for="username">用户名</label>
                            <input type="text" class="form-control" id="username" value="<?php echo htmlspecialchars($user['username']); ?>" disabled>
                            <small class="form-text text-muted">用户名不可更改</small>
                        </div>
                        <div class="form-group">
                            <label for="email">电子邮件</label>
                            <input type="email" class="form-control" id="email" name="email" value="<?php echo htmlspecialchars($user['email']); ?>" required>
                        </div>
                        
                        <hr class="my-4">
                        <h5 class="mb-3">修改密码</h5>
                        
                        <div class="form-group">
                            <label for="current_password">当前密码</label>
                            <input type="password" class="form-control" id="current_password" name="current_password">
                            <small class="form-text text-muted">如果要修改密码，请输入当前密码</small>
                        </div>
                        <div class="form-group">
                            <label for="new_password">新密码</label>
                            <input type="password" class="form-control" id="new_password" name="new_password">
                            <small class="form-text text-muted">密码长度至少为6个字符</small>
                        </div>
                        <div class="form-group">
                            <label for="confirm_password">确认新密码</label>
                            <input type="password" class="form-control" id="confirm_password" name="confirm_password">
                        </div>
                        
                        <button type="submit" class="btn btn-primary">保存修改</button>
                    </form>
                </div>
            </div>
        </div>
    </div>
</div>

<?php require_once 'footer.php'; ?> 